{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text"
   },
   "source": [
    "# Structured data classification with FeatureSpace\n",
    "\n",
    "**Author:** [fchollet](https://twitter.com/fchollet)<br>\n",
    "**Date created:** 2022/11/09<br>\n",
    "**Last modified:** 2022/11/09<br>\n",
    "**Description:** Classify tabular data in a few lines of code."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text"
   },
   "source": [
    "## Introduction\n",
    "\n",
    "This example demonstrates how to do structured data classification\n",
    "(also known as tabular data classification), starting from a raw\n",
    "CSV file. Our data includes numerical features,\n",
    "and integer categorical features, and string categorical features.\n",
    "We will use the utility `keras.utils.FeatureSpace` to index,\n",
    "preprocess, and encode our features.\n",
    "\n",
    "The code is adapted from the example\n",
    "[Structured data classification from scratch](https://keras.io/examples/structured_data/structured_data_classification_from_scratch/).\n",
    "While the previous example managed its own low-level feature preprocessing and\n",
    "encoding with Keras preprocessing layers, in this example we\n",
    "delegate everything to `FeatureSpace`, making the workflow\n",
    "extremely quick and easy.\n",
    "\n",
    "### The dataset\n",
    "\n",
    "[Our dataset](https://archive.ics.uci.edu/ml/datasets/heart+Disease) is provided by the\n",
    "Cleveland Clinic Foundation for Heart Disease.\n",
    "It's a CSV file with 303 rows. Each row contains information about a patient (a\n",
    "**sample**), and each column describes an attribute of the patient (a **feature**). We\n",
    "use the features to predict whether a patient has a heart disease\n",
    "(**binary classification**).\n",
    "\n",
    "Here's the description of each feature:\n",
    "\n",
    "Column| Description| Feature Type\n",
    "------------|--------------------|----------------------\n",
    "Age | Age in years | Numerical\n",
    "Sex | (1 = male; 0 = female) | Categorical\n",
    "CP | Chest pain type (0, 1, 2, 3, 4) | Categorical\n",
    "Trestbpd | Resting blood pressure (in mm Hg on admission) | Numerical\n",
    "Chol | Serum cholesterol in mg/dl | Numerical\n",
    "FBS | fasting blood sugar in 120 mg/dl (1 = true; 0 = false) | Categorical\n",
    "RestECG | Resting electrocardiogram results (0, 1, 2) | Categorical\n",
    "Thalach | Maximum heart rate achieved | Numerical\n",
    "Exang | Exercise induced angina (1 = yes; 0 = no) | Categorical\n",
    "Oldpeak | ST depression induced by exercise relative to rest | Numerical\n",
    "Slope | Slope of the peak exercise ST segment | Numerical\n",
    "CA | Number of major vessels (0-3) colored by fluoroscopy | Both numerical & categorical\n",
    "Thal | 3 = normal; 6 = fixed defect; 7 = reversible defect | Categorical\n",
    "Target | Diagnosis of heart disease (1 = true; 0 = false) | Target"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text"
   },
   "source": [
    "## Setup"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "colab_type": "code"
   },
   "outputs": [],
   "source": [
    "import os\n",
    "\n",
    "os.environ[\"KERAS_BACKEND\"] = \"tensorflow\"\n",
    "\n",
    "import tensorflow as tf\n",
    "import pandas as pd\n",
    "import keras\n",
    "from keras.utils import FeatureSpace"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text"
   },
   "source": [
    "## Preparing the data\n",
    "\n",
    "Let's download the data and load it into a Pandas dataframe:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "colab_type": "code"
   },
   "outputs": [],
   "source": [
    "# 对代码进行了注释，csv文件已经下载\n",
    "# file_url = \"http://storage.googleapis.com/download.tensorflow.org/data/heart.csv\"\n",
    "file_url = 'heart.csv'\n",
    "dataframe = pd.read_csv(file_url)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text"
   },
   "source": [
    "The dataset includes 303 samples with 14 columns per sample\n",
    "(13 features, plus the target label):"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "colab_type": "code"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "(303, 14)\n"
     ]
    }
   ],
   "source": [
    "print(dataframe.shape)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text"
   },
   "source": [
    "Here's a preview of a few samples:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "colab_type": "code"
   },
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>age</th>\n",
       "      <th>sex</th>\n",
       "      <th>cp</th>\n",
       "      <th>trestbps</th>\n",
       "      <th>chol</th>\n",
       "      <th>fbs</th>\n",
       "      <th>restecg</th>\n",
       "      <th>thalach</th>\n",
       "      <th>exang</th>\n",
       "      <th>oldpeak</th>\n",
       "      <th>slope</th>\n",
       "      <th>ca</th>\n",
       "      <th>thal</th>\n",
       "      <th>target</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>63</td>\n",
       "      <td>1</td>\n",
       "      <td>1</td>\n",
       "      <td>145</td>\n",
       "      <td>233</td>\n",
       "      <td>1</td>\n",
       "      <td>2</td>\n",
       "      <td>150</td>\n",
       "      <td>0</td>\n",
       "      <td>2.3</td>\n",
       "      <td>3</td>\n",
       "      <td>0</td>\n",
       "      <td>fixed</td>\n",
       "      <td>0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>67</td>\n",
       "      <td>1</td>\n",
       "      <td>4</td>\n",
       "      <td>160</td>\n",
       "      <td>286</td>\n",
       "      <td>0</td>\n",
       "      <td>2</td>\n",
       "      <td>108</td>\n",
       "      <td>1</td>\n",
       "      <td>1.5</td>\n",
       "      <td>2</td>\n",
       "      <td>3</td>\n",
       "      <td>normal</td>\n",
       "      <td>1</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>67</td>\n",
       "      <td>1</td>\n",
       "      <td>4</td>\n",
       "      <td>120</td>\n",
       "      <td>229</td>\n",
       "      <td>0</td>\n",
       "      <td>2</td>\n",
       "      <td>129</td>\n",
       "      <td>1</td>\n",
       "      <td>2.6</td>\n",
       "      <td>2</td>\n",
       "      <td>2</td>\n",
       "      <td>reversible</td>\n",
       "      <td>0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>37</td>\n",
       "      <td>1</td>\n",
       "      <td>3</td>\n",
       "      <td>130</td>\n",
       "      <td>250</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>187</td>\n",
       "      <td>0</td>\n",
       "      <td>3.5</td>\n",
       "      <td>3</td>\n",
       "      <td>0</td>\n",
       "      <td>normal</td>\n",
       "      <td>0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>41</td>\n",
       "      <td>0</td>\n",
       "      <td>2</td>\n",
       "      <td>130</td>\n",
       "      <td>204</td>\n",
       "      <td>0</td>\n",
       "      <td>2</td>\n",
       "      <td>172</td>\n",
       "      <td>0</td>\n",
       "      <td>1.4</td>\n",
       "      <td>1</td>\n",
       "      <td>0</td>\n",
       "      <td>normal</td>\n",
       "      <td>0</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "   age  sex  cp  trestbps  chol  fbs  restecg  thalach  exang  oldpeak  slope  \\\n",
       "0   63    1   1       145   233    1        2      150      0      2.3      3   \n",
       "1   67    1   4       160   286    0        2      108      1      1.5      2   \n",
       "2   67    1   4       120   229    0        2      129      1      2.6      2   \n",
       "3   37    1   3       130   250    0        0      187      0      3.5      3   \n",
       "4   41    0   2       130   204    0        2      172      0      1.4      1   \n",
       "\n",
       "   ca        thal  target  \n",
       "0   0       fixed       0  \n",
       "1   3      normal       1  \n",
       "2   2  reversible       0  \n",
       "3   0      normal       0  \n",
       "4   0      normal       0  "
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "dataframe.head()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text"
   },
   "source": [
    "The last column, \"target\", indicates whether the patient\n",
    "has a heart disease (1) or not (0).\n",
    "\n",
    "Let's split the data into a training and validation set:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {
    "colab_type": "code"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Using 242 samples for training and 61 for validation\n"
     ]
    }
   ],
   "source": [
    "val_dataframe = dataframe.sample(frac=0.2, random_state=1337)\n",
    "train_dataframe = dataframe.drop(val_dataframe.index)\n",
    "\n",
    "print(\n",
    "    \"Using %d samples for training and %d for validation\"\n",
    "    % (len(train_dataframe), len(val_dataframe))\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "dataframe.sample 生成样本，random_state 是随机数种子"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text"
   },
   "source": [
    "Let's generate `tf.data.Dataset` objects for each dataframe:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {
    "colab_type": "code"
   },
   "outputs": [],
   "source": [
    "\n",
    "def dataframe_to_dataset(dataframe):\n",
    "    dataframe = dataframe.copy()\n",
    "    labels = dataframe.pop(\"target\")\n",
    "    ds = tf.data.Dataset.from_tensor_slices((dict(dataframe), labels))\n",
    "    ds = ds.shuffle(buffer_size=len(dataframe))\n",
    "    return ds\n",
    "\n",
    "\n",
    "train_ds = dataframe_to_dataset(train_dataframe)\n",
    "val_ds = dataframe_to_dataset(val_dataframe)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "函数返回的是一个数据集，每个元素是一个包含特征和标签的元组"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text"
   },
   "source": [
    "Each `Dataset` yields a tuple `(input, target)` where `input` is a dictionary of features\n",
    "and `target` is the value `0` or `1`:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {
    "colab_type": "code"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Input: {'age': <tf.Tensor: shape=(), dtype=int64, numpy=57>, 'sex': <tf.Tensor: shape=(), dtype=int64, numpy=1>, 'cp': <tf.Tensor: shape=(), dtype=int64, numpy=4>, 'trestbps': <tf.Tensor: shape=(), dtype=int64, numpy=110>, 'chol': <tf.Tensor: shape=(), dtype=int64, numpy=201>, 'fbs': <tf.Tensor: shape=(), dtype=int64, numpy=0>, 'restecg': <tf.Tensor: shape=(), dtype=int64, numpy=0>, 'thalach': <tf.Tensor: shape=(), dtype=int64, numpy=126>, 'exang': <tf.Tensor: shape=(), dtype=int64, numpy=1>, 'oldpeak': <tf.Tensor: shape=(), dtype=float64, numpy=1.5>, 'slope': <tf.Tensor: shape=(), dtype=int64, numpy=2>, 'ca': <tf.Tensor: shape=(), dtype=int64, numpy=0>, 'thal': <tf.Tensor: shape=(), dtype=string, numpy=b'fixed'>}\n",
      "Target: tf.Tensor(0, shape=(), dtype=int64)\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "2024-08-04 21:48:15.083291: I tensorflow/core/framework/local_rendezvous.cc:404] Local rendezvous is aborting with status: OUT_OF_RANGE: End of sequence\n"
     ]
    }
   ],
   "source": [
    "for x, y in train_ds.take(1):\n",
    "    print(\"Input:\", x)\n",
    "    print(\"Target:\", y)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text"
   },
   "source": [
    "Let's batch the datasets:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {
    "colab_type": "code"
   },
   "outputs": [],
   "source": [
    "train_ds = train_ds.batch(32)\n",
    "val_ds = val_ds.batch(32)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text"
   },
   "source": [
    "## Configuring a `FeatureSpace`\n",
    "\n",
    "To configure how each feature should be preprocessed,\n",
    "we instantiate a `keras.utils.FeatureSpace`, and we\n",
    "pass to it a dictionary that maps the name of our features\n",
    "to a string that describes the feature type.\n",
    "\n",
    "We have a few \"integer categorical\" features such as `\"FBS\"`,\n",
    "one \"string categorical\" feature (`\"thal\"`),\n",
    "and a few numerical features, which we'd like to normalize\n",
    "-- except `\"age\"`, which we'd like to discretize into\n",
    "a number of bins.\n",
    "\n",
    "We also use the `crosses` argument\n",
    "to capture *feature interactions* for some categorical\n",
    "features, that is to say, create additional features\n",
    "that represent value co-occurrences for these categorical features.\n",
    "You can compute feature crosses like this for arbitrary sets of\n",
    "categorical features -- not just tuples of two features.\n",
    "Because the resulting co-occurences are hashed\n",
    "into a fixed-sized vector, you don't need to worry about whether\n",
    "the co-occurence space is too large."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {
    "colab_type": "code"
   },
   "outputs": [],
   "source": [
    "feature_space = FeatureSpace(\n",
    "    features={\n",
    "        # Categorical features encoded as integers\n",
    "        \"sex\": \"integer_categorical\",\n",
    "        \"cp\": \"integer_categorical\",\n",
    "        \"fbs\": \"integer_categorical\",\n",
    "        \"restecg\": \"integer_categorical\",\n",
    "        \"exang\": \"integer_categorical\",\n",
    "        \"ca\": \"integer_categorical\",\n",
    "        # Categorical feature encoded as string\n",
    "        \"thal\": \"string_categorical\",\n",
    "        # Numerical features to discretize\n",
    "        \"age\": \"float_discretized\",\n",
    "        # Numerical features to normalize\n",
    "        \"trestbps\": \"float_normalized\",\n",
    "        \"chol\": \"float_normalized\",\n",
    "        \"thalach\": \"float_normalized\",\n",
    "        \"oldpeak\": \"float_normalized\",\n",
    "        \"slope\": \"float_normalized\",\n",
    "    },\n",
    "    # We create additional features by hashing\n",
    "    # value co-occurrences for the\n",
    "    # following groups of categorical features.\n",
    "    crosses=[(\"sex\", \"age\"), (\"thal\", \"ca\")],\n",
    "    # The hashing space for these co-occurrences\n",
    "    # wil be 32-dimensional.\n",
    "    crossing_dim=32,\n",
    "    # Our utility will one-hot encode all categorical\n",
    "    # features and concat all features into a single\n",
    "    # vector (one vector per sample).\n",
    "    output_mode=\"concat\",\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text"
   },
   "source": [
    "## Further customizing a `FeatureSpace`\n",
    "\n",
    "Specifying the feature type via a string name is quick and easy,\n",
    "but sometimes you may want to further configure the preprocessing\n",
    "of each feature. For instance, in our case, our categorical\n",
    "features don't have a large set of possible values -- it's only\n",
    "a handful of values per feature (e.g. `1` and `0` for the feature `\"FBS\"`),\n",
    "and all possible values are represented in the training set.\n",
    "As a result, we don't need to reserve an index to represent \"out of vocabulary\" values\n",
    "for these features -- which would have been the default behavior.\n",
    "Below, we just specify `num_oov_indices=0` in each of these features\n",
    "to tell the feature preprocessor to skip \"out of vocabulary\" indexing.\n",
    "\n",
    "Other customizations you have access to include specifying the number of\n",
    "bins for discretizing features of type `\"float_discretized\"`,\n",
    "or the dimensionality of the hashing space for feature crossing."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {
    "colab_type": "code"
   },
   "outputs": [],
   "source": [
    "feature_space = FeatureSpace(\n",
    "    features={\n",
    "        # Categorical features encoded as integers\n",
    "        \"sex\": FeatureSpace.integer_categorical(num_oov_indices=0),\n",
    "        \"cp\": FeatureSpace.integer_categorical(num_oov_indices=0),\n",
    "        \"fbs\": FeatureSpace.integer_categorical(num_oov_indices=0),\n",
    "        \"restecg\": FeatureSpace.integer_categorical(num_oov_indices=0),\n",
    "        \"exang\": FeatureSpace.integer_categorical(num_oov_indices=0),\n",
    "        \"ca\": FeatureSpace.integer_categorical(num_oov_indices=0),\n",
    "        # Categorical feature encoded as string\n",
    "        \"thal\": FeatureSpace.string_categorical(num_oov_indices=0),\n",
    "        # Numerical features to discretize\n",
    "        \"age\": FeatureSpace.float_discretized(num_bins=30),\n",
    "        # Numerical features to normalize\n",
    "        \"trestbps\": FeatureSpace.float_normalized(),\n",
    "        \"chol\": FeatureSpace.float_normalized(),\n",
    "        \"thalach\": FeatureSpace.float_normalized(),\n",
    "        \"oldpeak\": FeatureSpace.float_normalized(),\n",
    "        \"slope\": FeatureSpace.float_normalized(),\n",
    "    },\n",
    "    # Specify feature cross with a custom crossing dim.\n",
    "    crosses=[\n",
    "        FeatureSpace.cross(feature_names=(\"sex\", \"age\"), crossing_dim=64),\n",
    "        FeatureSpace.cross(\n",
    "            feature_names=(\"thal\", \"ca\"),\n",
    "            crossing_dim=16,\n",
    "        ),\n",
    "    ],\n",
    "    output_mode=\"concat\",\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text"
   },
   "source": [
    "## Adapt the `FeatureSpace` to the training data\n",
    "\n",
    "Before we start using the `FeatureSpace` to build a model, we have\n",
    "to adapt it to the training data. During `adapt()`, the `FeatureSpace` will:\n",
    "\n",
    "- Index the set of possible values for categorical features.\n",
    "- Compute the mean and variance for numerical features to normalize.\n",
    "- Compute the value boundaries for the different bins for numerical features to discretize.\n",
    "\n",
    "Note that `adapt()` should be called on a `tf.data.Dataset` which yields dicts\n",
    "of feature values -- no labels."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {
    "colab_type": "code"
   },
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "2024-08-04 21:53:32.576686: I tensorflow/core/framework/local_rendezvous.cc:404] Local rendezvous is aborting with status: OUT_OF_RANGE: End of sequence\n",
      "2024-08-04 21:53:32.636078: I tensorflow/core/framework/local_rendezvous.cc:404] Local rendezvous is aborting with status: OUT_OF_RANGE: End of sequence\n",
      "2024-08-04 21:53:32.723933: I tensorflow/core/framework/local_rendezvous.cc:404] Local rendezvous is aborting with status: OUT_OF_RANGE: End of sequence\n",
      "2024-08-04 21:53:32.921853: I tensorflow/core/framework/local_rendezvous.cc:404] Local rendezvous is aborting with status: OUT_OF_RANGE: End of sequence\n"
     ]
    }
   ],
   "source": [
    "train_ds_with_no_labels = train_ds.map(lambda x, _: x)\n",
    "feature_space.adapt(train_ds_with_no_labels)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text"
   },
   "source": [
    "At this point, the `FeatureSpace` can be called on a dict of raw feature values, and will return a\n",
    "single concatenate vector for each sample, combining encoded features and feature crosses."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {
    "colab_type": "code"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "preprocessed_x.shape: (32, 138)\n",
      "preprocessed_x.dtype: <dtype: 'float32'>\n"
     ]
    }
   ],
   "source": [
    "for x, _ in train_ds.take(1):\n",
    "    preprocessed_x = feature_space(x)\n",
    "    print(\"preprocessed_x.shape:\", preprocessed_x.shape)\n",
    "    print(\"preprocessed_x.dtype:\", preprocessed_x.dtype)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text"
   },
   "source": [
    "## Two ways to manage preprocessing: as part of the `tf.data` pipeline, or in the model itself\n",
    "\n",
    "There are two ways in which you can leverage your `FeatureSpace`:\n",
    "\n",
    "### Asynchronous preprocessing in `tf.data`\n",
    "\n",
    "You can make it part of your data pipeline, before the model. This enables asynchronous parallel\n",
    "preprocessing of the data on CPU before it hits the model. Do this if you're training on GPU or TPU,\n",
    "or if you want to speed up preprocessing. Usually, this is always the right thing to do during training.\n",
    "\n",
    "### Synchronous preprocessing in the model\n",
    "\n",
    "You can make it part of your model. This means that the model will expect dicts of raw feature\n",
    "values, and the preprocessing batch will be done synchronously (in a blocking manner) before the\n",
    "rest of the forward pass. Do this if you want to have an end-to-end model that can process\n",
    "raw feature values -- but keep in mind that your model will only be able to run on CPU,\n",
    "since most types of feature preprocessing (e.g. string preprocessing) are not GPU or TPU compatible.\n",
    "\n",
    "Do not do this on GPU / TPU or in performance-sensitive settings. In general, you want to do in-model\n",
    "preprocessing when you do inference on CPU.\n",
    "\n",
    "In our case, we will apply the `FeatureSpace` in the tf.data pipeline during training, but we will\n",
    "do inference with an end-to-end model that includes the `FeatureSpace`."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text"
   },
   "source": [
    "Let's create a training and validation dataset of preprocessed batches:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {
    "colab_type": "code"
   },
   "outputs": [],
   "source": [
    "preprocessed_train_ds = train_ds.map(\n",
    "    lambda x, y: (feature_space(x), y), num_parallel_calls=tf.data.AUTOTUNE\n",
    ")\n",
    "preprocessed_train_ds = preprocessed_train_ds.prefetch(tf.data.AUTOTUNE)\n",
    "\n",
    "preprocessed_val_ds = val_ds.map(\n",
    "    lambda x, y: (feature_space(x), y), num_parallel_calls=tf.data.AUTOTUNE\n",
    ")\n",
    "preprocessed_val_ds = preprocessed_val_ds.prefetch(tf.data.AUTOTUNE)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text"
   },
   "source": [
    "## Build a model\n",
    "\n",
    "Time to build a model -- or rather two models:\n",
    "\n",
    "- A training model that expects preprocessed features (one sample = one vector)\n",
    "- An inference model that expects raw features (one sample = dict of raw feature values)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {
    "colab_type": "code"
   },
   "outputs": [],
   "source": [
    "dict_inputs = feature_space.get_inputs()\n",
    "encoded_features = feature_space.get_encoded_features()\n",
    "\n",
    "x = keras.layers.Dense(32, activation=\"relu\")(encoded_features)\n",
    "x = keras.layers.Dropout(0.5)(x)\n",
    "predictions = keras.layers.Dense(1, activation=\"sigmoid\")(x)\n",
    "\n",
    "training_model = keras.Model(inputs=encoded_features, outputs=predictions)\n",
    "training_model.compile(\n",
    "    optimizer=\"adam\", loss=\"binary_crossentropy\", metrics=[\"accuracy\"]\n",
    ")\n",
    "\n",
    "inference_model = keras.Model(inputs=dict_inputs, outputs=predictions)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text"
   },
   "source": [
    "## Train the model\n",
    "\n",
    "Let's train our model for 50 epochs. Note that feature preprocessing is happening\n",
    "as part of the tf.data pipeline, not as part of the model."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {
    "colab_type": "code"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Epoch 1/20\n",
      "8/8 - 1s - 63ms/step - accuracy: 0.6446 - loss: 0.6280 - val_accuracy: 0.7705 - val_loss: 0.5377\n",
      "Epoch 2/20\n",
      "8/8 - 0s - 12ms/step - accuracy: 0.6860 - loss: 0.5762 - val_accuracy: 0.7541 - val_loss: 0.4963\n",
      "Epoch 3/20\n",
      "8/8 - 0s - 11ms/step - accuracy: 0.7314 - loss: 0.5171 - val_accuracy: 0.7705 - val_loss: 0.4657\n",
      "Epoch 4/20\n",
      "8/8 - 0s - 11ms/step - accuracy: 0.8058 - loss: 0.4858 - val_accuracy: 0.7869 - val_loss: 0.4404\n",
      "Epoch 5/20\n",
      "8/8 - 0s - 11ms/step - accuracy: 0.8058 - loss: 0.4578 - val_accuracy: 0.7869 - val_loss: 0.4198\n",
      "Epoch 6/20\n",
      "8/8 - 0s - 11ms/step - accuracy: 0.7975 - loss: 0.4344 - val_accuracy: 0.7869 - val_loss: 0.4040\n",
      "Epoch 7/20\n",
      "8/8 - 0s - 11ms/step - accuracy: 0.8223 - loss: 0.4178 - val_accuracy: 0.7869 - val_loss: 0.3921\n",
      "Epoch 8/20\n",
      "8/8 - 0s - 11ms/step - accuracy: 0.8264 - loss: 0.3891 - val_accuracy: 0.7869 - val_loss: 0.3834\n",
      "Epoch 9/20\n",
      "8/8 - 0s - 12ms/step - accuracy: 0.8223 - loss: 0.3872 - val_accuracy: 0.7705 - val_loss: 0.3773\n",
      "Epoch 10/20\n",
      "8/8 - 0s - 11ms/step - accuracy: 0.8306 - loss: 0.3634 - val_accuracy: 0.8033 - val_loss: 0.3714\n",
      "Epoch 11/20\n",
      "8/8 - 0s - 12ms/step - accuracy: 0.8471 - loss: 0.3652 - val_accuracy: 0.8033 - val_loss: 0.3666\n",
      "Epoch 12/20\n",
      "8/8 - 0s - 12ms/step - accuracy: 0.8471 - loss: 0.3449 - val_accuracy: 0.8033 - val_loss: 0.3628\n",
      "Epoch 13/20\n",
      "8/8 - 0s - 12ms/step - accuracy: 0.8678 - loss: 0.3218 - val_accuracy: 0.8033 - val_loss: 0.3603\n",
      "Epoch 14/20\n",
      "8/8 - 0s - 13ms/step - accuracy: 0.8719 - loss: 0.3185 - val_accuracy: 0.8197 - val_loss: 0.3585\n",
      "Epoch 15/20\n",
      "8/8 - 0s - 12ms/step - accuracy: 0.8636 - loss: 0.2989 - val_accuracy: 0.8197 - val_loss: 0.3583\n",
      "Epoch 16/20\n",
      "8/8 - 0s - 12ms/step - accuracy: 0.8719 - loss: 0.2993 - val_accuracy: 0.8197 - val_loss: 0.3588\n",
      "Epoch 17/20\n",
      "8/8 - 0s - 12ms/step - accuracy: 0.8802 - loss: 0.2888 - val_accuracy: 0.8033 - val_loss: 0.3586\n",
      "Epoch 18/20\n",
      "8/8 - 0s - 12ms/step - accuracy: 0.8802 - loss: 0.2840 - val_accuracy: 0.7869 - val_loss: 0.3583\n",
      "Epoch 19/20\n",
      "8/8 - 0s - 12ms/step - accuracy: 0.8884 - loss: 0.2787 - val_accuracy: 0.8033 - val_loss: 0.3587\n",
      "Epoch 20/20\n",
      "8/8 - 0s - 15ms/step - accuracy: 0.8926 - loss: 0.2744 - val_accuracy: 0.8197 - val_loss: 0.3590\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "<keras.src.callbacks.history.History at 0x3104b0c90>"
      ]
     },
     "execution_count": 16,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "training_model.fit(\n",
    "    preprocessed_train_ds,\n",
    "    epochs=20,\n",
    "    validation_data=preprocessed_val_ds,\n",
    "    verbose=2,\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text"
   },
   "source": [
    "We quickly get to 80% validation accuracy."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text"
   },
   "source": [
    "## Inference on new data with the end-to-end model\n",
    "\n",
    "Now, we can use our inference model (which includes the `FeatureSpace`)\n",
    "to make predictions based on dicts of raw features values, as follows:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {
    "colab_type": "code"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\u001b[1m1/1\u001b[0m \u001b[32m━━━━━━━━━━━━━━━━━━━━\u001b[0m\u001b[37m\u001b[0m \u001b[1m0s\u001b[0m 114ms/step\n",
      "This particular patient had a 56.50% probability of having a heart disease, as evaluated by our model.\n"
     ]
    }
   ],
   "source": [
    "sample = {\n",
    "    \"age\": 60,\n",
    "    \"sex\": 1,\n",
    "    \"cp\": 1,\n",
    "    \"trestbps\": 145,\n",
    "    \"chol\": 233,\n",
    "    \"fbs\": 1,\n",
    "    \"restecg\": 2,\n",
    "    \"thalach\": 150,\n",
    "    \"exang\": 0,\n",
    "    \"oldpeak\": 2.3,\n",
    "    \"slope\": 3,\n",
    "    \"ca\": 0,\n",
    "    \"thal\": \"fixed\",\n",
    "}\n",
    "\n",
    "input_dict = {name: tf.convert_to_tensor([value]) for name, value in sample.items()}\n",
    "predictions = inference_model.predict(input_dict)\n",
    "\n",
    "print(\n",
    "    f\"This particular patient had a {100 * predictions[0][0]:.2f}% probability \"\n",
    "    \"of having a heart disease, as evaluated by our model.\"\n",
    ")"
   ]
  }
 ],
 "metadata": {
  "accelerator": "GPU",
  "colab": {
   "collapsed_sections": [],
   "name": "structured_data_classification_with_feature_space",
   "private_outputs": false,
   "provenance": [],
   "toc_visible": true
  },
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.9"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 0
}
